"""
Author: Jian SuiYue kaohx0214@yeah.net
Date: 2025-04-23 22:27:25
LastEditTime: 2025-05-23 18:17:28
FilePath: LibraryManagerStudio/cli.py
"""
import os
import sys
from typing import Optional

import typer
import uvicorn
from rich import print as rich_print
from typing_extensions import Annotated

from .version import VERSION

app = typer.Typer(help="Library Manager Studio System code rows")


def get_env_file_path():
    """
    Get env file path
    """
    app_dir = os.path.join(os.path.expanduser("~"), ".LibraryManagerStudio")
    # app_dir: 'C:\\Users\\10495\\.LibraryManagerStudio'
    if not os.path.exists(app_dir):
        os.makedirs(app_dir, exist_ok=True)
    return os.path.join(app_dir, "temp_env_vars.env")


@app.command()
def ui(
        host: str = "0.0.0.0",
        port: int = 8081,
        workers: int = 1,
        reload: Annotated[bool, typer.Option("--reload")] = False,
        docs: bool = True,
        appdir: str = None,
        database_uri: Optional[str] = None,
        upgrade_database: bool = False
):
    """
    Start library manager studio windows。
    
    :param host: (str, optional): host. default: 127.0.0.1
    :param port: (int, optional): port. default: 8081
    :param workers: (int, optional): person num. default: 1
    :param reload: (bool, optional): reload while running application to update code. default: False
    :param docs: (bool, optional): Whether to generate API docs. Default: True
    :param appdir: (str, optional): Path to the Library Manager Studio app directory. Default to None.
    :param database_uri: (str, optional): database url to conntect. default none
    :param upgrade_database: (bool, optional): upgrade database. Default False
    """

    # 写入配置
    env_vars = {
        "LIBRARYMANAGERSTUDIO_HOST": host,
        "LIBRARYMANAGERSTUDIO_PORT": port,
        "LIBRARYMANAGERSTUDIO_API_DOCS": str(docs),
    }
    if appdir:
        env_vars["LIBRARYMANAGERSTUDIO_APPDIR"] = appdir
    if database_uri:
        env_vars["LIBRARYMANAGERSTUDIO_DATABASE_URI"] = database_uri
    if upgrade_database:
        env_vars["LIBRARYMANAGERSTUDIO_UPGRADE_DATABASE"] = "1"
    # 创建临时环境文件以与uvicorn工作进程共享配置
    env_file_path = get_env_file_path()
    with open(env_file_path, "w", encoding="utf-8") as temp_env:
        for key, value in env_vars.items():
            temp_env.write(f"{key}={value}\n")

    # 获取当前脚本的目录
    current_dir = os.path.dirname(os.path.abspath(__file__))

    # 添加当前目录到Python路径
    if current_dir not in sys.path:
        sys.path.insert(0, current_dir)

    try:
        app_module = os.path.join(current_dir, "web", "app.py")
        if os.path.exists(app_module):
            typer.echo(f"Loding application: {app_module}")

        uvicorn.run(
            "LibraryManagerStudio.web.app:app",
            host=host,
            port=port,
            workers=workers,
            reload=reload,
            reload_excludes=["**/alembic/*", "**/alembic.ini", "**/versions/*"] if reload else None,
            env_file=env_file_path,
        )
    except ImportError as e:
        rich_print(f"[bold red]Error: Can't not import package: {str(e)}[/bold red]")
        sys.exit(1)
    except Exception as e:
        rich_print(f"[bold red]Error while start server: {str(e)}[/bold red]")
        sys.exit(1)


@app.command()
def version():
    """
    图书馆管理系统的版本。
    """
    rich_print(f"[bold green]Library Manager System[/bold green] version: {VERSION}")


@app.command()
def h():
    """
    帮助
    """
    rich_print(f"[bold red]Help? help 个锤子[/bold red] :boom:" \
               "\nOh right, if you have a question,\nplase send email to " \
               "[bold blue]kaohx0214@yeah.net[bold blue]")


def run():
    """作为包入口点的主函数"""
    app()


if __name__ == "__main__":
    run()
